<template>
    <div class="app-container">


        <!-- 添加或修改用户配置对话框 -->
        <el-row>
            <el-col :span="20">
                <h3>{{form.title}}</h3>
            </el-col>

            <el-col :span="2">
                <el-button type="primary" size="mini" @click="submitForm">保 存</el-button>
            </el-col>
            <el-col :span="2">
                <el-button type="danger" size="mini" @click="cancel">取 消</el-button>
            </el-col>
        </el-row>

        <el-button size="small" @click="addTab(editableTabsValue)">
            添加一天行程
        </el-button>

        <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" closable @tab-remove="removeTab">
            <el-tab-pane v-for="(item,index1) in editableTabs" :key="item.name" :label="item.title" :name="item.name">
                <el-form>
                <el-row style="margin-bottom: 10px;">
                    
                    <el-col :span="6"> <el-form-item label="日期" prop="region">
                    <el-date-picker
                    v-model="item.date"
                    type="date"
                    placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                </el-col>
                <el-col :span="6"> 
                    
                </el-col>
                </el-row>
            </el-form>

                <el-form ref="form" v-for="(itemContent,index2) in item.content" :key="index2"   label-width="80px">

                    <el-row>
                        <el-col :span="6">
                        <el-form-item label="景点选择" prop="region">
                            <el-select @change="change(index1,index2)" v-model="itemContent.id" placeholder="请选择类型" maxlength="30" >
                       
                                <el-option
                                v-for="dict in scienicList"
                                :key="dict.id"
                                :label="dict.name"
                                :value="dict.id"

                                 /> 
                            </el-select>
                          </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="start" prop="region">
                                <el-time-picker
                                format = 'HH:mm'
                                value-format="HH:mm"
                                v-model="itemContent.startTime"
                                type="time"
                                placeholder="选择时间">
                                </el-time-picker>
                              </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="end" prop="region">
                                    <el-time-picker
                                    format = 'HH:mm'
                                    value-format="HH:mm"
                                    v-model="itemContent.endTime"
                                    type="time"
                                    placeholder="选择时间">
                                    </el-time-picker>
                                  </el-form-item>
                                </el-col>
                    </el-row>
                    <el-row >
                        
                        <el-col :span="6">
                            <el-form-item label="首图" prop="image">
                                <ImageUploadItem :value="itemContent.image" :index1="index1" :index2="index2" :limit="1" @input="geturl" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="18">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="英文名称" prop="title">
                                        <el-input readonly v-model="itemContent.name" placeholder="请输入英文名称" />

                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="中文名称" prop="titleCh">
                                        <el-input readonly v-model="itemContent.titleCh" placeholder="请输入中文名称" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="分数" prop="region">
                                        <el-input readonly :max="5" :min="1" type="number" v-model="itemContent.score" placeholder="请输入分数"
                                            maxlength="30" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="类型" prop="region">
                                        <el-input readonly v-model="itemContent.type" placeholder="请输入地区类型" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
        
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="Overview" prop="region">
                                        <el-input readonly type="textarea" v-model="itemContent.overview"></el-input>
                                    </el-form-item>
                                </el-col>
        
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="经度" prop="longitude">
                                        <el-input readonly v-model="itemContent.longitude"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="纬度" prop="latitude">
                                        <el-input readonly v-model="itemContent.latitude"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="备注" prop="region">
                                        <el-input readonly type="textarea" v-model="itemContent.remark"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-button type="danger" size="mini" @click="delItemContent(index1,index2)">删除</el-button>
                                </el-col>
                                
                            </el-row>
                        </el-col>
                    </el-row>
        
                </el-form>

                <el-button style="width: 100%;" type="success" size="mini" @click="additemContent(index1)">添 加</el-button>
            </el-tab-pane>
        </el-tabs>



        
    </div>
</template>

<script>
    import { listUser, add, update, get, getinfo, del } from "@/api/front/guid";

    import { listUser as  scieniclist} from "@/api/front/scienic";

    import { listUser as catelist } from "@/api/front/cate";
    import { listUser as regionlist } from "@/api/front/region";
    import { getToken } from "@/utils/auth";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// 图片上传组件
import ImageUploadItem from "@/components/ImageUploadItem"
    export default {
        name: "guidPlan",
        dicts: ['sys_normal_disable', 'sys_user_sex'],
        components: { Treeselect,ImageUploadItem },
        data() {
            return {
                scienicList:[],
                 // 查询参数
                 scienicQueryParams: {
                    pageNum: 1,
                    pageSize: 100
                },
                editableTabsValue: '1',
                editableTabs: [],
                tabIndex: 1,


                id: null,
                // 遮罩层
                loading: true,

                // 用户表格数据
                userList: null,

                // 表单参数
                form: {},
                defaultProps: {
                    children: "children",
                    label: "label"
                },

                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    userName: undefined,
                    phonenumber: undefined,
                    status: undefined,
                    deptId: undefined
                },
                // 列信息
                columns: [],
                // 表单校验
                rules: {},
                data: {},
                dayData: []
            };
        },
        watch: {
            // 根据名称筛选部门树
            deptName(val) {
                this.$refs.tree.filter(val);
            }
        },
        mounted() {
            // 通过 this.$route.query 获取参数
            this.id = this.$route.query.id;
            getinfo(this.id).then(res => {
                this.form = res.data
                if( res.data.plans){
                    this.editableTabs = res.data.plans
                }
            })
            scieniclist(this.scienicQueryParams).then(res=>{
                this.scienicList = res.rows;
            })
        },
        created() {
            //   this.getList();
            //   catelist(query).then(res=>{
            //     this.cateOption = res.rows;
            //   })

            //   regionlist(query).then(res=>{
            //     this.regionOption = res.rows;
            //   })
        },
        methods: {
            change(index1,index2){
                 // 获取当前选择的景点 ID
                let selectedId = this.editableTabs[index1].content[index2].id;

                 // 查找选中的景点信息
                 let selectedDict = this.scienicList.find(dict => dict.id === selectedId);

                 // 更新 selectedData 数组
                if (selectedDict) {
                    // this.editableTabs[index1].content[index2] = selectedDict
                    // this.editableTabs[index1].content[index2].scenicId = selectedId
                     // 直接更新 scenicId 和其他属性
                    this.$set(this.editableTabs[index1].content, index2, {
                        ...selectedDict,  // 展开选中的景点信息
                        id: selectedId  // 保持 scenicId 不变
                    });
                }
                console.log(this.editableTabs[index1])
                this.$forceUpdate()
            },
            additemContent(index){
                this.editableTabs[index].content.push({
                            image:"",
                            title:"",
                            titleCh:"",
                            score:"",
                            type:"",
                            overview:"",
                            remark:"",
                            endTime:"",
                            startTime:""
                        })
            },
            delItemContent(index1,index2){
                // 确保 index1 和 index2 在有效范围内
                if (index1 >= 0 && index1 < this.editableTabs.length) {
                const tab = this.editableTabs[index1];
                if (index2 >= 0 && index2 < tab.content.length) {
                    // 使用 splice 删除 content 数组中的指定项
                    tab.content.splice(index2, 1);
                } else {
                    console.error('Index2 is out of bounds');
                }
                } else {
                console.error('Index1 is out of bounds');
                }
            },
            addTab(targetName) {
                // console.log(this.editableTabs.length)
                
                let newTabName = (this.editableTabs!=[]?this.editableTabs.length:0)+1 + '';

                this.editableTabs.push({
                    title: '第 '+ newTabName + " 天",
                    name: newTabName,
                    content: [{
                    date:""
                    }]
                });
                this.editableTabsValue = newTabName;
            },
            removeTab(targetName) {
                let tabs = this.editableTabs;
                let activeName = this.editableTabsValue;
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.name;
                            }
                        }
                    });
                }

                this.editableTabsValue = activeName;
                this.editableTabs = tabs.filter(tab => tab.name !== targetName);
            },
            geturl(fileList, index1, index2) {
                console.log(index2)
                // console.log(this.editableTabs[index1].content[index2])
                this.editableTabs[index1].content[index2].image = fileList
                // this.form.image = fileList
            },
            /** 查询用户列表 */
            getList() {
                this.loading = true;
                listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                    this.userList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                }
                );
            },
            /** 查询部门下拉树结构 */
            getDeptTree() {
                // deptTreeSelect().then(response => {
                //   this.deptOptions = response.data;
                // });
            },
            // 筛选节点
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            // 节点单击事件
            handleNodeClick(data) {
                this.queryParams.deptId = data.id;
                this.handleQuery();
            },
            // 用户状态修改
            handleStatusChange(row) {
                let text = row.status === "0" ? "启用" : "停用";
                this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
                    return changeUserStatus(row.userId, row.status);
                }).then(() => {
                    this.$modal.msgSuccess(text + "成功");
                }).catch(function () {
                    row.status = row.status === "0" ? "1" : "0";
                });
            },
            /** 关闭按钮 */
                cancel() {
                    const obj = { path: "/guidList"};
                    this.$tab.closeOpenPage(obj);
                    
                },
            // 表单重置
            reset() {
                this.form = {};
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                this.queryParams.deptId = undefined;
                this.$refs.tree.setCurrentKey(null);
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.userId);
                this.single = selection.length != 1;
                this.multiple = !selection.length;
            },
            // 更多操作触发
            handleCommand(command, row) {
                switch (command) {
                    case "handleResetPwd":
                        this.handleResetPwd(row);
                        break;
                    case "handleAuthRole":
                        this.handleAuthRole(row);
                        break;
                    default:
                        break;
                }
            },
            /** 提交按钮 */
            submitForm: function () {
                this.form.plans = this.editableTabs
                add(this.form).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
         
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const userIds = row.id || this.ids;
                this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
                    return del(userIds);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => { });
            },
            /** 导出按钮操作 */
            handleExport() {
                this.download('system/user/export', {
                    ...this.queryParams
                }, `user_${new Date().getTime()}.xlsx`)
            },
            /** 导入按钮操作 */
            handleImport() {
                this.upload.title = "用户导入";
                this.upload.open = true;
            },
            /** 下载模板操作 */
            importTemplate() {
                this.download('system/user/importTemplate', {
                }, `user_template_${new Date().getTime()}.xlsx`)
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
                this.getList();
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            }
        }
    };
</script>